package ac.github.os.internal.core.selector.impl

import ac.github.os.api.common.SingleList
import ac.github.os.internal.core.condition.callVoid
import ac.github.os.internal.core.config.StringConfig
import ac.github.os.internal.core.config.get
import ac.github.os.internal.core.objective.EntityObjective
import ac.github.os.internal.core.objective.Objective
import ac.github.os.internal.core.selector.Selector
import ac.github.os.internal.core.trigger.LocationTrigger
import ac.github.os.internal.core.trigger.dynamic
import ac.github.os.internal.core.trigger.offset
import ac.github.os.internal.session.Cache
import ac.github.os.internal.session.Session
import org.bukkit.entity.LivingEntity
import taboolib.common.platform.Awake
import java.util.*
import kotlin.math.min

@Awake
class RangeSelector : Selector {
    override fun doSelect(session: Session, config: StringConfig) : SingleList<Objective> {

        return SingleList<Objective>().apply {

            val radius = config.get("radius", -1.0,single = true)!!
            val amount = config.get("amount", -1)!!
            val type = config.get("type", "AIR")!!.uppercase(Locale.getDefault())

            session.callVoid<LocationTrigger> {
                val listOf = arrayListOf<EntityObjective>()
                val location = it.location.dynamic(config)
                location.world?.getNearbyEntities(location, radius, radius, radius)?.forEach {
                    if (it is LivingEntity && (type == "AIR" || type == it.type.name)) {
                        listOf.add(EntityObjective(it))
                    }
                }
                if (amount != -1) {
                    listOf.subList(0, min(amount, listOf.size - 1))
                }
                addAll(listOf)
            }
        }
    }

    override val namespace: String
        get() = "range"
}